package cn.mock.random;

import cn.mock.constant.Constant;
import cn.mock.utils.FileUtils;
import cn.mock.utils.RandomUtils;
import cn.mock.utils.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author JiaZH
 * @date 2024-01-12
 */
public class RandomImage {

    private static final List<String> COLOR_VALUES;

    static {
        COLOR_VALUES = FileUtils.readAllLines("/color.txt");
    }

    /**
     * 生成一个随机的图片地址。
     * 替代图片源 http://fpoimg.com/
     *
     * @param size
     * @param background
     * @param foreground
     * @param format
     * @param text
     * @return
     */
    public static String getImage(String size, String background, String foreground, String format, String text) {
        format = StringUtils.defaultIfBlank(format, "");
        if (StringUtils.isBlank(size) || !Pattern.compile("\\dx\\d").matcher(size).matches()) {
            size = RandomUtils.pick(Constant.AD_SIZE);
        }
        if (StringUtils.isNotBlank(background) && StringUtils.startsWith(background, "#")) {
            background = StringUtils.substringAfter(background, "#");
        }
        if (StringUtils.isNotBlank(foreground) && StringUtils.startsWith(foreground, "#")) {
            foreground = StringUtils.substringAfter(foreground, "#");
        }
        if (!Pattern.compile("png|jpg|gif").matcher(format.toLowerCase()).find()) {
            format = "";
        }
        StringBuilder builder = new StringBuilder(Constant.IMAGE_BASE_URL);
        builder.append(size);
        if (StringUtils.isNotBlank(background)) {
            builder.append("/").append(background);
        }
        if (StringUtils.isNotBlank(foreground)) {
            builder.append("/").append(foreground);
        }
        if (StringUtils.isNotBlank(format)) {
            builder.append(".").append(format);
        }
        if (StringUtils.isNotBlank(text)) {
            builder.append("&text=").append(text);
        }
        return builder.toString();
    }

    /**
     * 生成一个随机的图片地址。
     *
     * @return
     */
    public static String getImg() {
        return getImage(null, null, null, null, null);
    }

    /**
     * 生成一段随机的 Base64 图片编码。
     *
     * @param size
     * @param text
     * @return
     */
    public static String getDataImage(String size, String text) {
        if (StringUtils.isBlank(size) || !Pattern.compile("\\dx\\d").matcher(size).matches()) {
            size = RandomUtils.pick(Constant.AD_SIZE);
        }
        if (StringUtils.isBlank(text)) {
            text = size;
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        String[] sizes = size.split("x");
        int index = RandomBasic.getInt(0, COLOR_VALUES.size() - 1);

        int width = Integer.parseInt(sizes[0]);
        int height = Integer.parseInt(sizes[1]);
        String background = COLOR_VALUES.get(index);
        String foreground = "#FFF";
        int textSize = 14;
        String font = "sans-serif";

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = (Graphics2D) image.getGraphics();

        graphics.setBackground(Color.decode(background));
        graphics.clearRect(0, 0, width, height);
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        Font textFont = new Font(font, Font.PLAIN, textSize);
        graphics.setFont(textFont);
        FontMetrics fm = graphics.getFontMetrics(textFont);
        int textWidth = fm.stringWidth(text);
        int widthX = (width - textWidth) / 2;
        int heightY = height / 2 + (height > 100 ? 8 : 4);
        //阴影颜色
        graphics.setPaint(new Color(0, 0, 0, 64));
        //先绘制阴影
        graphics.drawString(text, widthX, heightY);
        //正文颜色
        graphics.setPaint(Color.decode(foreground));
        graphics.drawString(text, widthX, heightY);

        try {
            ImageIO.write(image, "png", os);
            return Base64.getEncoder().encodeToString(os.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                System.err.println("出现异常：" + e);
            }
        }
    }

    /**
     * 生成一段随机的 Base64 图片编码。
     *
     * @return
     */
    public static String getDataImage() {
        return getDataImage(null, null);
    }

}
